<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-21
 * Time: 上午9:24
 */

namespace api\modules\chedai\controllers;


use common\components\increment\Config;
use common\components\increment\Huirong;
use common\components\tools\Tools;
use common\models\AliFaceValidate;
use common\models\credit_app\Order;
use common\models\Unionpay3002SetLog;
use common\models\workin\IdcardCheck;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;

class UnionpayController extends Controller
{
    /**
     * 获取人脸识别3002的认证回调数据获取
     * @desc 主要为根据手机设备上采集的身份证号，中文姓名，样本照片，验证本人的相似度的回调获取。
     * @param string $orderId 订单号
     */
    public function actionGet3002($orderId)
    {
        $data =  \Yii::$app->cache->get('orderId_'.$orderId);
        if (!$data){
            throw new ErrorException("没有回调结果");
        }
        $log = Unionpay3002SetLog::findOne(['order_id' => $data['_respData']['orderId']]);
        if (!$log){
            throw new ErrorException("get3002 没有记录请求");
        }
        $log->last_get_time = time();
        $log->save();
        $data['score'] = $data['_respData']['score'];
        return $data;
    }

    /**
     * 根据身份证号 获取人脸识别3002的最新认证回调数据获取
     * @desc 主要为根据手机设备上采集的身份证号，中文姓名，样本照片，验证本人的相似度的回调获取。
     * @param string $id_card 身份证号
     * @param int $is_last 是否选最新的
     * @return Unionpay3002SetLog|array
     * status 10:有相似度获取的最新相似度,11:没有该身份证号的请求,12:没有相似度
     */
    public function actionGet3002ByIdCard($id_card, $is_last = 0)
    {
        /**
         * @var Unionpay3002SetLog $x
         */
        $__x = Unionpay3002SetLog::find()->where(['id_card' => $id_card])->orderBy(['score'=>SORT_DESC, 'p_at'=>SORT_DESC]);
        $x = $__x->one();
        $count = $__x->count();
        if (!$x){
            $_x = Unionpay3002SetLog::find()->one();
            $x = $_x->toArray();
            $x['status'] = 11;
            $x['status_msg'] = "没有该身份证号的请求";
            return $x;
        }
        if ($is_last){
            $__y = Unionpay3002SetLog::find()->where(['id_card' => $id_card, 'status_message' => "业务处理成功"])->count();
            if ($__y>0){
                $x->status_message = "业务处理成功";
            }
        }
        if(!$x->score){
            if (time() - $x->p_at > 180){
                if ($count >= 3){
                    $x = $x->toArray();
                    $x['status'] = 12;
                    $x['status_msg'] = "超过三次，请钉钉申请人工审核";
                    return $x;
                }else{
                    $x = $x->toArray();
                    $x['status'] = 12;
                    $x['status_msg'] = "请重新人脸识别确保完成整个过程";
                }
                return $x;
            }else{
                $x = $x->toArray();
                $x['status'] = 13;
                $x['status_msg'] = "等待相似度";
                return $x;
            }
        }
        $x->last_get_time = time();
        $x->save();
        if (!$x->score){
            $x->score = 0;
        }
//        $x->score = 120;
        $y = $x->toArray();
        $y['status'] = 10;
        $y['status_msg'] = "有相似度";
        return $y;
    }

    /**
     * 根据订单号获取所有人的实时面签值[app使用]
     * @desc get/post
     * @param string $o_id dyhl_order
     * @param int $is_idcard_check 是否在scroe<70%进行汇融查询
     * @param int $is_last 是否选最新的
     * @return array
     */
    public function actionOrdersGet3002($o_id, $is_idcard_check = 0, $is_last = 0)
    {
        $out = [];
        $order = Order::findOne(['o_id'=>$o_id]);
        if (!$order){
            return $out;
        }
        foreach ($order->certs as $k => $v){
            $id_card = $v->ct_code;
            $__x = $this->actionGet3002ByIdCard($id_card, $is_last);
            $__x['ct_id'] = $v->ct_id;
            $__x['ct_name'] = $v->ct_name;
            $__x['ct_code'] = $v->ct_code;
            if ($is_idcard_check){
                if ($__x['scroe'] < 70){
                    $model = IdcardCheck::findOne(['id_card'=>$v->ct_code, 'name'=>$v->ct_name]);
                    if (!$model){
                        $model = new IdcardCheck();
                        $model->grant_key = Config::$huirong['grantKey'];
                        $model->api_key = Config::$huirong['id_card_check0'];
                        $model->order_report_id = \Yii::$app->security->generateRandomString(32).rand(10000000,99999999);
                        $model->name = $v->ct_name;
                        $model->id_card = $v->ct_name;
                        $model->search_index = date("YmdHis").\Yii::$app->security->generateRandomString(10);
                        $huirong = new Huirong();
                        $huirong->model2 = $model;
                        $r = $huirong->idcardCheck0();
                        $_r = json_decode($r->content);
                        if ($_r->code==0){
                            if ($_r->data->orderReportId==$model->order_report_id){
                                $huirong->model2->result_detail = $r->content;
                                $huirong->model2->result_photo_base64 = $_r->data->photoBase64;
                                $huirong->model2->result_result = $_r->data->result;
                                $huirong->model2->result_report_id = $_r->data->reportId;
//                        $huirong->model2->result_auth_status = $_r->data->authStatus;
                                $huirong->model2->result_is_real = $_r->data->isReal;
                                $huirong->model2->result_service_fee = $_r->data->serviceFee;
                                $huirong->model2->result_exp_status = $_r->data->expStatus;
                                $huirong->model2->result_busi_code = $_r->data->busiCode;
                                $huirong->model2->result_busi_msg = $_r->data->busiMsg;
                                if (isset($_r->data->extendData))$huirong->model2->result_extend_data = $_r->data->extendData;
                                if ($huirong->model2->save()){}else{
                                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($huirong->model2));
                                }
                            }else{
                                throw new ErrorException("结果的orderReportId与请求的order_report_id不符");
                            }
                        }else{
                            throw new ErrorException($_r->msg."[".$r->content."]");
                        }
                    }
                    $__x['idcard_check'] = $model->toArray();
                }
            }
            if ($__x)$out[] = $__x;
        }
        return  $out;
    }

    /**
     * 修改人脸识别日志状态
     * desc get/post
     * @param string $order_id 3002表的order_id字段
     * @param string|null $status_message 状态
     * @return array
     * @throws ErrorException
     */
    public function actionStatusUpdate3002($order_id, $status_message = null)
    {
        $model = Unionpay3002SetLog::findOne(['order_id'=>$order_id]);
        if (!$model){
            throw new ErrorException("没有找到对应记录");
        }
        $model->status_message = $status_message;
        if ($model->save()){
            return [
                'is_update' => 1,
            ];
        }else{
            throw new ErrorException(var_export($model->errors, true));
        }
        /*$ali = \Yii::$app->runAction('chedai/ali/get-ali-face-validate-by-idcard', ['idcard' => $model->id_card]);
        $ali = $ali['data'];
        $audit = $ali['ali_fv']['audit'];
        if ($audit == AliFaceValidate::AUDIT_PASS){
            $model->status_message = $status_message;
            if ($model->save()){
                return [
                    'audit' => $audit,
                    'is_update' => 1,
                ];
            }else{
                throw new ErrorException(var_export($model->errors, true));
            }
        }else{
            return [
                'audit' => $audit,
                'is_update' => 0,
            ];
        }*/
    }
}